/**
 * 
 */
package com.iwgame.websgs.framework.utils;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;

import com.iwgame.websgs.framework.constant.SpaceConstant;
import com.iwgame.websgs.framework.exception.ServiceException;
import com.iwgame.websgs.framework.property.ReaderProperties;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * @ClassName: FileUtils
 * @Description: 
 * @author wuzejian jasno.wuzj@gmail.com
 * @date 2011-9-5 下午3:52:02
 * 
 */
public class FileUtils {
	
	private static File FILE_BOY_1 = null;
	private static File FILE_BOY_2 = null;
	private static File FILE_BOY_3 = null;
	private static File FILE_GIRL_1 = null;
	private static File FILE_GIRL_2 = null;
	private static File FILE_GIRL_3 = null;
	
	private static String SYSPATH = "";
	
	private static String FILE_PERFIX_1 = "." + SpaceConstant.AVATAR_DEFAULT_SUFFIX;
	private static String FILE_PERFIX_2 = "_33." + SpaceConstant.AVATAR_DEFAULT_SUFFIX;
	private static String FILE_PERFIX_3 = "_16." + SpaceConstant.AVATAR_DEFAULT_SUFFIX;
	static{
		SYSPATH = ReaderProperties.getValue("websgs_data_home") + File.separator + "avatar" + File.separator;
//		SYSPATH = "C:\\xxxx\\";
		
		FILE_BOY_1 = new File(SYSPATH + SpaceConstant.AVATAR_BOY_100);
		FILE_BOY_2 = new File(SYSPATH + SpaceConstant.AVATAR_BOY_50);
		FILE_BOY_3 = new File(SYSPATH + SpaceConstant.AVATAR_BOY_25);

		FILE_GIRL_1 = new File(SYSPATH + SpaceConstant.AVATAR_GIRL_100);
		FILE_GIRL_2 = new File(SYSPATH + SpaceConstant.AVATAR_GIRL_50);
		FILE_GIRL_3 = new File(SYSPATH + SpaceConstant.AVATAR_GIRL_25);
	}

	/**
	 * 写文件操作，根据指定的输出路径，把File对象写入文件中
	 * 
	 * @param srcFile
	 *            原文件
	 * @param outAbsolutePath
	 *            输出文件绝对路径
	 * @return 返回值<=0表示失败
	 * @throws IOException
	 */
	public static int saveFile(File srcFile, String outAbsolutePath)
			throws IOException {
		try {
			OutputStream os = new FileOutputStream(outAbsolutePath);
			InputStream is = new FileInputStream(srcFile);
			return IOUtils.copy(is, os);
		} catch (IOException e) {
			throw e;
		}
	}

	/**
	 * 写文件  
	 * @param file 
	 * @param newJson
	 */
	public static void print(File file, String newJson) {
		Scanner sc = null;
		PrintWriter pw = null;
		try {
			if (!file.exists()) {// 如果文件不存在,则新建.
				File parentDir = new File(file.getParent());
				if (!parentDir.exists())// 如果所在目录不存在,则新建.
					parentDir.mkdirs();
				file.createNewFile();
			}
			// sc = new Scanner(file);
			// StringBuilder sb = new StringBuilder();
			// while (sc.hasNextLine()){// 先读出旧文件内容,并暂存sb中;
			// sb.append(sc.nextLine());
			// sb.append("\r\n");// 换行符作为间隔,扫描器读不出来,因此要自己添加.
			// }
			// sc.close();

			pw = new PrintWriter(new FileWriter(file), true);
			// /* A. */pw.println(sb.toString());// ,写入旧文件内容.
			/* B. */
			pw.println(newJson);// 写入新日志.
			/*
			 * 如果先写入A,最近日志在文件最后. 如是先写入B,最近日志在文件最前.
			 */
			pw.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 
	 * @param fileName
	 * @param content
	 */
	public static void appendToFile(String fileName, String content) {
		OutputStreamWriter outputStream = null;
		File file = new File(fileName);
		if (!file.exists()) {// 如果文件不存在,则新建.
			File parentDir = new File(file.getParent());
			if (!parentDir.exists())// 如果所在目录不存在,则新建.
				parentDir.mkdirs();
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			outputStream = new OutputStreamWriter(new FileOutputStream( fileName, true), "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			outputStream.write(content);
		} catch (IOException e) {
			// TODO Auto-generated catch block
		} finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * @param filePath
	 *            图片所在的文件夹路径
	 * @param filelist
	 *            图片路径
	 * @param ext
	 *            扩展名
	 * @param n
	 *            图片名
	 * @param newW
	 *            目标宽
	 * @param newH
	 *            目标高
	 * @param per
	 *            百分比
	 */
	public static void tosmallerpic(String filePath, BufferedImage bufferedImage, String ext, String n, int newW, int newH, float per) {
		try {
			String img_midname = filePath + n + "." + ext;

			BufferedImage tag = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(
				bufferedImage.getScaledInstance(newW, newH, Image.SCALE_SMOOTH), 
				0,
				0, 
				null);
			
			FileOutputStream newimage = new FileOutputStream(img_midname); // 输出到文件流
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
			JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
			
			jep.setQuality(per, true); // 压缩质量
			encoder.encode(tag, jep);
			newimage.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 根据用户的ID 计算用户的头像放置的文件名
	 * @param uid
	 * @return
	 */
	public static String getAvatarFileName(long uid){
		if (uid <= 0 )
			throw new ServiceException("根据用户ID获取头像放置的文件名错误,[uid="+uid+"]");
		if (uid > 0 && uid % 10000 == 0) {
			return String.valueOf(uid / 10000);
		} else {
			return String.valueOf(uid / 10000 + 1);
		}
	}

	/**
	 * 放大和缩小图片大小(指定多少高度和宽度)
	 * @param file
	 * @param redrawImage
	 * @param redrawWidth
	 * @param redrawHeight
	 */
	private static void RedrawFast(BufferedImage bufImage, String redrawImage, int redrawWidth, int redrawHeight) {
//		try {
//			Image image = ImageIO.read(file);
//
//			// 选择一种图像缩放算法，在这种缩放算法中，缩放速度比缩放平滑度具有更高的优先级。
//			bufImage.getGraphics().drawImage(
//				image.getScaledInstance(
//					redrawWidth, 
//					redrawHeight,
//					Image.SCALE_DEFAULT
//				), 
//				0, 
//				0, 
//				null);
//		} catch (IOException ex) {
//			ex.printStackTrace();
//		}
	}
	
	/**
	 * 创建用户头像文件
	 * @param uid
	 * @author caisheng
	 * @return
	 */
	public static void buildAvatarFile(long uid, int sexType) throws IOException{
		String newPath = SYSPATH + getAvatarFileName(uid) + File.separator ;
		File folder = new File(newPath);
		if(!folder.exists()){
			folder.mkdir();
		}
		switch (sexType) {
			case SpaceConstant.SEX_FEMALE:
				org.apache.commons.io.FileUtils.copyFile(FILE_GIRL_1, new File(newPath + uid + FILE_PERFIX_1));
				org.apache.commons.io.FileUtils.copyFile(FILE_GIRL_2, new File(newPath + uid + FILE_PERFIX_2));
				org.apache.commons.io.FileUtils.copyFile(FILE_GIRL_3, new File(newPath + uid + FILE_PERFIX_3));
				break;
			case SpaceConstant.SEX_MALE:
			default:
				org.apache.commons.io.FileUtils.copyFile(FILE_BOY_1, new File(newPath + uid + FILE_PERFIX_1));
				org.apache.commons.io.FileUtils.copyFile(FILE_BOY_2, new File(newPath + uid + FILE_PERFIX_2));
				org.apache.commons.io.FileUtils.copyFile(FILE_BOY_3, new File(newPath + uid + FILE_PERFIX_3));
				break;
		}
	}
}